package com.example.finalproject.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.example.finalproject.bean.LoginBean;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_NAME = "MySQLite.db";
    private static String create_users = "create table users(username varchar(32), password varchar(32))";
    private static DatabaseHelper instance;

    private DatabaseHelper(@Nullable Context context) {
        super(context, DB_NAME, null, 1);
    }

    public static synchronized DatabaseHelper getInstance(Context context) {
        if (instance == null) {
            instance = new DatabaseHelper(context.getApplicationContext());
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(create_users);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public long register(LoginBean loginBean) {
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", loginBean.getUserName());
        cv.put("password", loginBean.getPassword());
        return sqLiteDatabase.insert("users", null, cv);
    }

    public boolean login(String username, String password) {
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        Cursor users = sqLiteDatabase.query("users", null, "username like ?", new String[]{username}, null, null, null);
        if (users != null) {
            while (users.moveToNext()) {
                String savedPassword = users.getString(1);
                users.close();
                return savedPassword.equals(password);
            }
        }
        return false;
    }

    public int update(String username, String oldPassword, String newPassword) {
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        ContentValues cv = new ContentValues();
        if (login(username, oldPassword)) {
            cv.put("username", username);
            cv.put("password", newPassword);
            return sqLiteDatabase.update("users", cv, "username = ?", new String[]{username});
        } else {
            return -1;
        }
    }
}
